package dao;

import entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import tool.MyBatisUtil;

import java.io.Reader;

public class UserDaoImpl implements UserDao {

    SqlSessionFactoryBuilder builder=null;
    SqlSessionFactory factory=null;
    SqlSession sqlSession=null;
    //输入流读取配置文件
    Reader reader=null;
    public int getcount() {
        int result=-1;
        try{
            //读取配置文件
            reader= Resources.getResourceAsReader("mybatis-config.xml");
            //构键builder
            builder=new SqlSessionFactoryBuilder();
            //构键factory
            factory=builder.build(reader);
            //构键sqlSession
            sqlSession=factory.openSession();
            //执行数据库的操作dao接口的全限定名+id名
            //result=sqlSession.selectOne("dao.UserDao.findall");
            result=sqlSession.getMapper(UserDao.class).getcount();
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }finally {
            //释放资源
            sqlSession.close();
        }
    }

    @Override
    public User getUser(Integer userid) {
        User user=null;
        try{

            //构键sqlSession
            sqlSession= MyBatisUtil.getSession();
            //执行数据库的操作dao接口的全限定名+id名
            //result=sqlSession.selectOne("dao.UserDao.findall");
            user=sqlSession.getMapper(UserDao.class).getUser(userid);
            return user;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            //释放资源
            MyBatisUtil.closeSession();
        }
    }
}
